﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.ComponentModel;
using System.Collections.Specialized;
using AssignmentsManage.Converters;
using System.IO;
using System.Configuration;

namespace AssignmentsManage
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window, INotifyPropertyChanged
    {
        #region Constructor

        public MainWindow()
        {
            App.Current.Resources.MergedDictionaries.Clear();
            ResourceDictionary newDict = new ResourceDictionary();
            //AssignmentsManage.Properties.Settings.Default.currentTheme = AssignmentsManage.Properties.Settings.Default.Properties["currentTheme"].DefaultValue.ToString();
            newDict.Source = new Uri(AssignmentsManage.Properties.Settings.Default.currentTheme);
            ((App)Application.Current).Resources.MergedDictionaries.Add(newDict);

            //AssignmentsManage.Properties.Settings.Default.Reset();
            //AssignmentsManage.Properties.Settings.Default.settingsInitialized = true;
            InitializeComponent();
            DataHolder = new DataClasses.DataHolder();


            //Try load settings from previous version
            if (AssignmentsManage.Properties.Settings.Default.settingsInitialized == false)
            {
                foreach (SettingsProperty p in AssignmentsManage.Properties.Settings.Default.Properties)
                {
                    AssignmentsManage.Properties.Settings.Default.Upgrade();
                }
                AssignmentsManage.Properties.Settings.Default.settingsInitialized = true;
            }

            this.Height = (double)AssignmentsManage.Properties.Settings.Default.MainWinSize.Height;
            this.Width = (double)AssignmentsManage.Properties.Settings.Default.MainWinSize.Width;
            this.WindowState = (System.Windows.WindowState)AssignmentsManage.Properties.Settings.Default.MainWinState;
        }

        #endregion

        #region Properties

        public DataClasses.DataHolder DataHolder
        {
            get
            {
                return (DataClasses.DataHolder)this.Resources["DataHolderRes"];
            }
            set
            {
                this.Resources["DataHolderRes"] = value;
            }
        }

        public int ItemsShown
        {
            get
            {
                return lstActivities.Items.Count;
            }
        }

        #endregion

        #region Main Buttons

        /// <summary>
        /// Show the Add Course dialog and create a new course
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAddCourse_Click(object sender, RoutedEventArgs e)
        {
            Windows.CourseWindow courseWin = new Windows.CourseWindow();
            courseWin.Owner = this;
            courseWin.ActivityWorths = new System.Collections.ObjectModel.ObservableCollection<DataClasses.ActivityTypeWorth>();
            for (int i = 0; i < Enum.GetValues(typeof(DataClasses.EnumInfo.ActivityType)).Length; i++)
            {
                courseWin.ActivityWorths.Add(new DataClasses.ActivityTypeWorth((DataClasses.EnumInfo.ActivityType)i));
            }
            courseWin.CustomProperties = new System.Collections.ObjectModel.ObservableCollection<SetCLib.TitleValueXML>();
            courseWin.ShowDialog();
            if (courseWin.DialogResult == true)
            {
                var test = DataHolder.getCourseByCode(courseWin.txtCourseCode.Text);
                if (DataHolder.getCourseByCode(courseWin.txtCourseCode.Text) == null)
                {
                    DataHolder.CourseList.Add(new DataClasses.Course(courseWin.txtCourseCode.Text, courseWin.txtTitle.Text, courseWin.cpColourID.SelectedColor));
                    DataHolder.CourseList[DataHolder.CourseList.Count - 1].ActivityTypeWorths = courseWin.ActivityWorths.ToList<DataClasses.ActivityTypeWorth>();
                    courseWin.CustomProperties.RemoveAt(courseWin.CustomProperties.Count - 1);
                    DataHolder.CourseList[DataHolder.CourseList.Count - 1].CustomProperties = courseWin.CustomProperties.ToList<SetCLib.TitleValueXML>();
                }
                else
                {
                    MessageBox.Show("This course code is already in use. New courses must use a unique code to identify them.", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                    btnAddCourse_Click(sender, e);
                }
            }
        }

        /// <summary>
        /// Show the Add Activity dialog and create a new activity
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAddActivity_Click(object sender, RoutedEventArgs e)
        {
            //cboFilter.SelectedIndex = 0;
            DataClasses.Activity newActivity = new DataClasses.Activity();
            DataHolder.ActivityList.Add(newActivity);
            lstActivities.SelectedItem = newActivity;
            lstActivities.ScrollIntoView(lstActivities.SelectedItem);
            OnPropertyChanged("ItemsShown");
            //SetCategoryCollpasedForAll();
        }

        /// <summary>
        /// Show the setup dialog window
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSetup_Click(object sender, RoutedEventArgs e)
        {
            Windows.SetupWindow setupWin = new Windows.SetupWindow();
            setupWin.Owner = this;

            foreach (ComboBoxItem item in setupWin.cboThemes.Items)
            {
                if (item.Tag.ToString() == AssignmentsManage.Properties.Settings.Default.currentTheme)
                {
                    setupWin.cboThemes.SelectedItem = item;
                    break;
                }
            }

            setupWin.ShowDialog();
            if (setupWin.DialogResult == true)
            {
                if (!String.IsNullOrEmpty(setupWin.txtFilePath.Text))
                {
                    if (System.IO.File.Exists(setupWin.txtFilePath.Text))
                    {
                        //Use the old file
                        AssignmentsManage.Properties.Settings.Default.filePath = setupWin.txtFilePath.Text;
                        DataHolder = DataClasses.DataLoader.LoadFromFile(setupWin.txtFilePath.Text);
                        MainUpdateContentBindings();
                    }
                    else
                    {
                        //Use a new file
                        AssignmentsManage.Properties.Settings.Default.filePath = setupWin.txtFilePath.Text;
                        DataHolder = DataClasses.DataLoader.CreateNewFile(setupWin.txtFilePath.Text);
                        if (DataHolder == null)
                        {
                            MessageBox.Show("Error creating a new file");
                        }

                        MainUpdateContentBindings();
                    }
                }

                if (setupWin.ResetColumnOrderSet)
                {
                    AssignmentsManage.Properties.Settings.Default.columnOrder = AssignmentsManage.Properties.Settings.Default.columnOrderDefault;
                    LoadColumnOrder();
                }

                if (setupWin.ChangeTheme)
                {
                    AssignmentsManage.Properties.Settings.Default.currentTheme = ((ComboBoxItem)setupWin.cboThemes.SelectedItem).Tag.ToString();
                    MessageBox.Show("You need to restart the application for theme changes to take effect.", "Theme Changed", MessageBoxButton.OK, MessageBoxImage.Information);
                }
            }
        }

        /// <summary>
        /// Save all courses and activities to the file
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSave_Click(object sender, RoutedEventArgs e)
        {
            DataClasses.DataLoader.SaveToFile(AssignmentsManage.Properties.Settings.Default.filePath, DataHolder);
        }

        /// <summary>
        /// Show the about dialog window
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAbout_Click(object sender, RoutedEventArgs e)
        {
            Windows.AboutWindow aboutwin = new Windows.AboutWindow();
            aboutwin.Owner = this;
            aboutwin.ShowDialog();
        }

        #endregion

        #region ListBox Handlers

        private void lstActivities_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            foreach (object item in e.RemovedItems)
            {
                if (item.GetType() == typeof(DataClasses.Activity))
                {
                    ((DataClasses.Activity)item).EditingStatus_Extra = false;
                    ((DataClasses.Activity)item).EditingStatus_Multiple = false;
                }
            }
            if (lstActivities.SelectedIndex > -1 && lstActivities.SelectedItems.Count == 1)
            {
                DataHolder.ActivityList[DataHolder.ActivityList.IndexOf((DataClasses.Activity)lstActivities.SelectedItem)].EditingStatus_Extra = true;
                DataHolder.ActivityList[DataHolder.ActivityList.IndexOf((DataClasses.Activity)lstActivities.SelectedItem)].EditingStatus_Multiple = false;
            }
            else if (lstActivities.SelectedItems.Count > 1)
            {
                foreach (object item in lstActivities.SelectedItems)
                {
                    DataHolder.ActivityList[DataHolder.ActivityList.IndexOf((DataClasses.Activity)item)].EditingStatus_Multiple = true;
                }
            }
        }

        private void lstCourses_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (((SetCLib.TitleValueItemCollection)ddbtnFilter.Resources["filter_source"])[2].Checked == true)
            {
                TitleValueItemCollection_ItemCheckedChanged(sender);
            }
        }

        /// <summary>
        /// Edit a course by double clicking on the course listbox
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void lstCourses_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            if (lstCourses.SelectedIndex > -1)
            {
                DataClasses.Course tmpCourse = ((DataClasses.Course)lstCourses.SelectedItem);
                int colIndex = DataHolder.CourseList.IndexOf(tmpCourse);

                Windows.CourseWindow coursewin = new Windows.CourseWindow();
                coursewin.Owner = this;
                coursewin.txtCourseCode.Text = tmpCourse.CourseCode;
                coursewin.txtTitle.Text = tmpCourse.Title;
                coursewin.cpColourID.SelectedColor = tmpCourse.IDColour;
                coursewin.ActivityWorths = new System.Collections.ObjectModel.ObservableCollection<DataClasses.ActivityTypeWorth>();
                coursewin.CustomProperties = new System.Collections.ObjectModel.ObservableCollection<SetCLib.TitleValueXML>();
                foreach (DataClasses.ActivityTypeWorth worth in tmpCourse.ActivityTypeWorths)
                {
                    coursewin.ActivityWorths.Add(new DataClasses.ActivityTypeWorth(worth.ActivityType, worth.Worth));
                }
                foreach (SetCLib.TitleValueXML tv in tmpCourse.CustomProperties)
                {
                    coursewin.CustomProperties.Add(new SetCLib.TitleValueXML(tv.Title, tv.Value));
                }

                coursewin.ShowDialog();
                if (coursewin.DialogResult == true)
                {
                    if (coursewin.txtCourseCode.Text == tmpCourse.CourseCode || DataHolder.getCourseByCode(coursewin.txtCourseCode.Text) == null)
                    {
                        DataHolder.replaceCourseCodeForActivities(tmpCourse.CourseCode, coursewin.txtCourseCode.Text);
                        DataHolder.CourseList[colIndex].CourseCode = coursewin.txtCourseCode.Text;
                        DataHolder.CourseList[colIndex].Title = coursewin.txtTitle.Text;
                        DataHolder.CourseList[colIndex].IDColour = coursewin.cpColourID.SelectedColor;
                        DataHolder.CourseList[colIndex].ActivityTypeWorths = coursewin.ActivityWorths.ToList<DataClasses.ActivityTypeWorth>();
                        coursewin.CustomProperties.RemoveAt(coursewin.CustomProperties.Count - 1);
                        DataHolder.CourseList[colIndex].CustomProperties = coursewin.CustomProperties.ToList<SetCLib.TitleValueXML>();
                        ((CollectionViewSource)this.Resources["collActivities"]).View.Refresh();
                    }
                    else
                    {
                        MessageBox.Show("This course code is already in use. New courses must use a unique code to identify them.", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                        btnAddCourse_Click(sender, e);
                    }
                }
            }
        }

        private void btnCourseItemDelete_Click(object sender, RoutedEventArgs e)
        {
            if (MessageBox.Show("Are you sure you would like to delete this course and any activities associated with it? The course and activities cannot be recovered.", "Delete Course", MessageBoxButton.YesNo, MessageBoxImage.Warning)
                == MessageBoxResult.Yes)
            {
                DataHolder.deleteCourse((DataClasses.Course)lstCourses.SelectedItem);

                MainUpdateContentBindings(true, true, false, false);
            }
        }

        private void mniDeleteCourse_Click(object sender, RoutedEventArgs e)
        {
            btnCourseItemDelete_Click(sender, e);
        }

        #endregion

        #region Activity Item Handlers

        private void btnActivityOK_Click(object sender, RoutedEventArgs e)
        {
            if (sender.GetType() == typeof(Button))
            {
                foreach (object item in lstActivities.SelectedItems)
                {
                    DataHolder.getCourseByCode(((DataClasses.Activity)item).CourseInCode).TotalGrade =
                        DataHolder.getTotalCourseGrade(((DataClasses.Activity)item).CourseInCode);
                }

                lstActivities.SelectedIndex = -1;
            }
            ((CollectionViewSource)this.Resources["collActivities"]).View.Refresh();
        }

        private void btnActivityDelete_Click(object sender, RoutedEventArgs e)
        {
            for (int i = lstActivities.SelectedItems.Count - 1; i >= 0; i--)
            {
                DataHolder.ActivityList.Remove((DataClasses.Activity)lstActivities.SelectedItems[i]);
            }
        }

        private void btnActivityComments_Click(object sender, RoutedEventArgs e)
        {
            Windows.CommentsWindow commentswin = new Windows.CommentsWindow();
            commentswin.txtTitle.Text = string.Format(commentswin.txtTitle.Text, ((DataClasses.Activity)lstActivities.SelectedItem).Title);
            commentswin.txtComments.Text = ((DataClasses.Activity)lstActivities.SelectedItem).Comments;
            commentswin.Owner = this;
            commentswin.ShowDialog();
            if (commentswin.DialogResult == true)
            {
                ((DataClasses.Activity)lstActivities.SelectedItem).Comments = commentswin.txtComments.Text;
            }
        }

        private void btnActivityLinkedFiles_Click(object sender, RoutedEventArgs e)
        {
            Windows.LinkedFilesWindow fileswin = new Windows.LinkedFilesWindow();
            fileswin.LinkedFiles = new System.Collections.ObjectModel.ObservableCollection<DataClasses.LinkedFile>(((DataClasses.Activity)lstActivities.SelectedItem).LinkedFiles);
            fileswin.Owner = this;
            fileswin.ShowDialog();
            if (fileswin.DialogResult == true)
            {
                ((DataClasses.Activity)lstActivities.SelectedItem).LinkedFiles = fileswin.LinkedFiles;
            }
        }

        private void lstActivities_Drop(object sender, DragEventArgs e)
        {
            FrameworkElement dropElement = (FrameworkElement)e.OriginalSource;
            if (dropElement.DataContext != null && dropElement.DataContext.GetType() == typeof(DataClasses.Activity))
            {
                DataClasses.Activity dropActivity = (DataClasses.Activity)dropElement.DataContext;

                if (e.Data.GetDataPresent(DataFormats.FileDrop))
                {
                    string[] droppedFilePaths =
                    e.Data.GetData(DataFormats.FileDrop, true) as string[];

                    foreach (string droppedFilePath in droppedFilePaths)
                    {
                        dropActivity.LinkedFiles.Add(new DataClasses.LinkedFile(droppedFilePath));
                    }
                }
                else if (e.Data.GetDataPresent(DataFormats.Text))
                {
                    string droppedText = e.Data.GetData(DataFormats.Text, true) as string;
                    if (Uri.IsWellFormedUriString(droppedText, UriKind.Absolute))
                    {
                        dropActivity.LinkedFiles.Add(new DataClasses.LinkedFile(droppedText, true));
                    }
                }
            }
        }

        private void lstActivities_DragOver(object sender, DragEventArgs e)
        {
            try
            {
                FrameworkElement dropElement = (FrameworkElement)e.OriginalSource;
                if (dropElement.DataContext != null && dropElement.DataContext.GetType() == typeof(DataClasses.Activity))
                {
                    e.Effects = DragDropEffects.Link;
                }
                else
                {
                    e.Effects = DragDropEffects.None;
                    e.Handled = true;
                }
            }
            catch 
            {
                e.Effects = DragDropEffects.None;
                e.Handled = true;
            }
        }

        #endregion

        #region Window Events

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            LoadColumnOrder();
            //cboFilter.SelectedIndex = AssignmentsManage.Properties.Settings.Default.selectedFilter;
            LoadFilters();
            ShowHideColumns();

            if (AssignmentsManage.Properties.Settings.Default.filePath != null &&
                AssignmentsManage.Properties.Settings.Default.filePath != String.Empty)
            {
                DataHolder = DataClasses.DataLoader.LoadFromFile(AssignmentsManage.Properties.Settings.Default.filePath);
                MainUpdateContentBindings(false, true, false, false);

                if (DataHolder == null)
                {
                    MessageBox.Show("The file containing activity and course data could not be found or is corrupt.\n\n" + AssignmentsManage.Properties.Settings.Default.filePath, "Error Loading File", MessageBoxButton.OK, MessageBoxImage.Error);
                    btnSetup_Click(sender, e);
                }
                else
                {
                    MainUpdateContentBindings();
                }
            }
            else
            {
                btnSetup_Click(sender, e);
            }
        }

        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            AssignmentsManage.Properties.Settings.Default.MainWinSize = 
                new System.Drawing.Size((int)this.Width, (int)this.Height);
            AssignmentsManage.Properties.Settings.Default.MainWinState = (int)this.WindowState;

            DataClasses.DataLoader.SaveToFile(AssignmentsManage.Properties.Settings.Default.filePath, DataHolder);
            SaveFilters();
            SaveColumnOrder();
            //AssignmentsManage.Properties.Settings.Default.selectedFilter = cboFilter.SelectedIndex;

            AssignmentsManage.Properties.Settings.Default.Save();
        }

        private void MainUpdateContentBindings(bool updateCourses = true, bool updateActivities = true, bool updateTitle = true, bool updateGrades = true)
        {
            if (updateCourses)
            {
                lstCourses.ItemsSource = DataHolder.CourseList;
            }

            if (updateActivities)
            {
                ((CollectionViewSource)this.Resources["collActivities"]).Source = DataHolder.ActivityList;
                ((CollectionViewSource)this.Resources["collActivities"]).View.Refresh();
                BindingOperations.GetBindingExpressionBase(runLastSave, Run.TextProperty).UpdateTarget();
                BindingOperations.GetBindingExpression(runTotalActivities, Run.TextProperty).UpdateTarget();
                ((CourseCodeToCoursePropertyConverter)this.Resources["CourseCodeToCoursePropertyConverter1"]).Holder = DataHolder;
                ((CourseCodeToCourseObjectConverter)this.Resources["CourseCodeToCourseObjectConverter1"]).Holder = DataHolder;
                OnPropertyChanged("ItemsShown");
            }

            if (updateTitle)
            {
                FileInfo info = new FileInfo(AssignmentsManage.Properties.Settings.Default.filePath);
                this.Title = "Assignment Manage - " + info.Name;
            }

            if (updateGrades)
            {
                foreach (object item in DataHolder.ActivityList)
                {
                    if (((DataClasses.Activity)item).DateCategory != "New Item")
                    {
                        DataHolder.getCourseByCode(((DataClasses.Activity)item).CourseInCode).TotalGrade =
                            DataHolder.getTotalCourseGrade(((DataClasses.Activity)item).CourseInCode);
                    }
                }
            }
        }

        #endregion

        #region Activity ListView

        #region Filtering

        private void TitleValueItemCollection_ItemCheckedChanged(object sender)
        {
            ddbtnFilter.IsOpen = false;
            string outputTitleA = "";
            string outputTitleB = "";
            string outputTitleC = "";

            foreach (SetCLib.TitleValueItem item in ((SetCLib.TitleValueItemCollection)ddbtnFilter.Resources["filter_source"]).Where(x => x.IsHeader == false))
            {
                if (item.Checked)
                {
                    if (item.Group == "FilterIn")
                    {
                        if (item.UID == "_All")
                        {
                            outputTitleC = "for all courses";
                        }
                        else
                        {
                            outputTitleC = "for selected course";
                        }
                    }
                    else if (item.Group == "ActivityType")
                    {
                        if (item.UID != "__ActivityAll")
                        {
                            outputTitleA = item.Title;
                        }
                        else
                        {
                            outputTitleA = "All activities";
                        }
                    }
                    else if (item.Group == "Status")
                    {
                        if (item.UID != "__StatusAll")
                        {
                            outputTitleB = item.Title.ToLower();
                        }
                    }
                }
            }

            ddbtnFilter.Content = outputTitleA + " " + outputTitleB + " " + outputTitleC;

            lstActivities.Items.Filter = delegate(Object obj)
                {
                    DataClasses.Activity activity = (DataClasses.Activity)obj;
                    bool isOk = false;

                    foreach (SetCLib.TitleValueItem item in ((SetCLib.TitleValueItemCollection)ddbtnFilter.Resources["filter_source"]).Where(x => x.Checked == true))
                    {
                        if (item.Group == "FilterIn")
                        {
                            if (item.UID == "_All")
                            {
                                isOk = true;
                            }
                            else if (item.UID == "_SelectedCourse")
                            {
                                string selCourseCode = lstCourses.SelectedIndex > -1 ? ((DataClasses.Course)lstCourses.SelectedItem).CourseCode : string.Empty;
                                if (activity.CourseInCode == selCourseCode) { isOk = true; }
                            }
                        }

                        if (item.Group == "ActivityType" && isOk == true)
                        {
                            if (item.UID == "__ActivityAll")
                            {
                                isOk = true;
                            }
                            else if (item.UID == "__Assignments")
                            {
                                if (activity.ActivityType == DataClasses.EnumInfo.ActivityType.Assignment) { isOk = true; } else { isOk = false; }
                            }
                            else if (item.UID == "__FinalExams")
                            {
                                if (activity.ActivityType == DataClasses.EnumInfo.ActivityType.FinalExam) { isOk = true; } else { isOk = false; }
                            }
                            else if (item.UID == "__Labs")
                            {
                                if (activity.ActivityType == DataClasses.EnumInfo.ActivityType.Lab) { isOk = true; } else { isOk = false; }
                            }
                            else if (item.UID == "__Midterms")
                            {
                                if (activity.ActivityType == DataClasses.EnumInfo.ActivityType.Midterm) { isOk = true; } else { isOk = false; }
                            }
                            else if (item.UID == "__Quizzes")
                            {
                                if (activity.ActivityType == DataClasses.EnumInfo.ActivityType.Quiz) { isOk = true; } else { isOk = false; }
                            }
                            else if (item.UID == "__Tests")
                            {
                                if (activity.ActivityType == DataClasses.EnumInfo.ActivityType.Test) { isOk = true; } else { isOk = false; }
                            }
                            else if (item.UID == "__ReadingAssignments")
                            {
                                if (activity.ActivityType == DataClasses.EnumInfo.ActivityType.ReadingAssignment) { isOk = true; } else { isOk = false; }
                            }
                        }

                        if (item.Group == "Status" && isOk == true)
                        {
                            if (item.UID == "__StatusAll")
                            {
                                isOk = true;
                            }
                            else if (item.UID == "__NotStarted")
                            {
                                if (activity.ActivityStatusType == DataClasses.EnumInfo.ActivityStatusType.NotStarted) { isOk = true; } else { isOk = false; }
                            }
                            else if (item.UID == "__InProgress")
                            {
                                if (activity.ActivityStatusType == DataClasses.EnumInfo.ActivityStatusType.InProgress) { isOk = true; } else { isOk = false; }
                            }
                            else if (item.UID == "__Studying")
                            {
                                if (activity.ActivityStatusType == DataClasses.EnumInfo.ActivityStatusType.Studying) { isOk = true; } else { isOk = false; }
                            }
                            else if (item.UID == "__Finished")
                            {
                                if (activity.ActivityStatusType == DataClasses.EnumInfo.ActivityStatusType.Finished) { isOk = true; } else { isOk = false; }
                            }
                            else if (item.UID == "__Graded")
                            {
                                if (activity.ActivityStatusType == DataClasses.EnumInfo.ActivityStatusType.Graded) { isOk = true; } else { isOk = false; }
                            }
                        }
                    }
                    return isOk;
                };
        }

        public void SaveFilters()
        {
            int index = 0;
            foreach (SetCLib.TitleValueItem item in ((SetCLib.TitleValueItemCollection)ddbtnFilter.Resources["filter_source"]).Where(x => x.IsHeader == false))
            {
                AssignmentsManage.Properties.Settings.Default.filtersSelected[index] = item.Checked.ToString();
                index++;
            }
        }

        public void LoadFilters()
        {
            int index = 0;
            foreach (SetCLib.TitleValueItem item in ((SetCLib.TitleValueItemCollection)ddbtnFilter.Resources["filter_source"]).Where(x => x.IsHeader == false))
            {
                item.Checked = bool.Parse(AssignmentsManage.Properties.Settings.Default.filtersSelected[index]);
                index++;
            }
        }

        private void hypResetFilters_Click(object sender, RoutedEventArgs e)
        {
            foreach (SetCLib.TitleValueItem item in ((SetCLib.TitleValueItemCollection)ddbtnFilter.Resources["filter_source"]).Where(x => x.IsHeader == false))
            {
                if (item.UID.Contains("All"))
                { 
                    item.Checked = true;
                }
                else
                {
                    item.Checked = false;
                }
            }
        }

        #endregion

        #region Sorting



        #endregion

        #region Columns

        /// <summary>
        /// Save the order of the Activity columns to application settings
        /// </summary>
        private void SaveColumnOrder()
        {
            AssignmentsManage.Properties.Settings.Default.columnOrder.Clear();

            foreach (GridViewColumn col in ((GridView)lstActivities.View).Columns)
            {
                AssignmentsManage.Properties.Settings.Default.columnOrder.Add(col.Header.ToString());
            }
        }

        /// <summary>
        /// Load the order of the Activity columns from application settings
        /// </summary>
        private void LoadColumnOrder()
        {
            int indexOn = 0;
            foreach (string s in AssignmentsManage.Properties.Settings.Default.columnOrder)
            {
                //search for the column
                for (int i = 0; i < ((GridView)lstActivities.View).Columns.Count; i++)
                {
                    if (((GridView)lstActivities.View).Columns[i].Header.ToString() == s)
                    {
                        ((GridView)lstActivities.View).Columns.Move(i, indexOn);
                        break;
                    }
                }

                indexOn++;
            }
        }

        /// <summary>
        /// Change the visible Activity columns when the column selection contextmenu closes
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ContextMenu_Unloaded(object sender, RoutedEventArgs e)
        {
            ShowHideColumns();
        }

        /// <summary>
        /// Show or hide Activity columns based on application settings
        /// </summary>
        private void ShowHideColumns()
        {

            foreach (SetCLib.TitleValue tv in AssignmentsManage.Properties.Settings.Default.columnVisiblity)
            {
                for (int i = 0; i < ((GridView)lstActivities.View).Columns.Count; i++)
                {
                    if (((GridView)lstActivities.View).Columns[i].Header.ToString() == tv.Title)
                    {
                        ((GridView)lstActivities.View).Columns[i].Width = tv.Visible == "True" ? Double.NaN : 0;
                    }
                }
            }
        }

        #endregion

        #region Category Expander

        private void expanderCategory_Collapsed(object sender, RoutedEventArgs e)
        {
            if (((CollectionViewGroup)((Expander)sender).DataContext).Name.ToString() != "New Item")
            {
                foreach (var item in ((CollectionViewGroup)((Expander)sender).DataContext).Items)
                {
                    (lstActivities.ItemContainerGenerator.ContainerFromItem(item) as ListViewItem).IsSelected = false;
                    ((DataClasses.Activity)item).EditingStatus_Extra = false;
                    ((DataClasses.Activity)item).EditingStatus_Multiple = false;
                }
                SetCollpased(((CollectionViewGroup)((Expander)sender).DataContext).Name.ToString(), true);
            }
        }

        private void expanderCategory_Expanded(object sender, RoutedEventArgs e)
        {
            SetCollpased(((CollectionViewGroup)((Expander)sender).DataContext).Name.ToString(), false);
        }

        private void expanderCategory_Loaded(object sender, RoutedEventArgs e)
        {
            if (((CollectionViewGroup)((Expander)sender).DataContext).Name.ToString() != "New Item")
            {
                ((Expander)sender).IsExpanded = !CategoryExists(((CollectionViewGroup)((Expander)sender).DataContext).Name.ToString());
            }
            else
            {
                ((Expander)sender).IsExpanded = true;
            }
        }

        //helper function
        private bool CategoryExists(string header)
        {
            return (AssignmentsManage.Properties.Settings.Default.categoriesCollapsed.Contains(header));
        }

        //helper function
        private void SetCollpased(string header, bool isCollpased)
        {
            if (!CategoryExists(header) && isCollpased)
            {
                AssignmentsManage.Properties.Settings.Default.categoriesCollapsed.Add(header);
            }
            else if (CategoryExists(header) && !isCollpased)
            {
                AssignmentsManage.Properties.Settings.Default.categoriesCollapsed.Remove(header);
            }
        }

        #endregion

        #endregion

        #region NotifyChanges

        // Create the OnPropertyChanged method to raise the event
        protected void OnPropertyChanged(string name)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(name));
            }
        }
        public event PropertyChangedEventHandler PropertyChanged;

        #endregion

    }
}
